package top.pengdong.pictureShare.gateway.config.security;

import cn.hutool.core.convert.Convert;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.ReactiveAuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.server.authorization.AuthorizationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import reactor.core.publisher.Mono;
import top.pengdong.pictureShare.common.model.SysConstant;

import java.net.URI;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
@Primary
public class JwtAccessManager implements ReactiveAuthorizationManager<AuthorizationContext> {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    private final AntPathMatcher matcher = new AntPathMatcher();

    @Override
    public Mono<AuthorizationDecision> check(Mono<Authentication> mono, AuthorizationContext authorizationContext) {
        //从Redis中获取当前路径可访问角色列表
        URI uri = authorizationContext.getExchange().getRequest().getURI();
        Object value = null;
//                redisTemplate.opsForHash().get(SysConstant.OAUTH_URLS, uri.getPath());

        // 这里应该使用全局 URI 匹配操作
        Map<Object, Object> entries = redisTemplate.opsForHash().entries(SysConstant.OAUTH_URLS);

        //TODO 这里有个顺序问题一定要记住，因为可能存在 /** 与 详细域名的冲突
        List<String> authorities = null;
        for(Object o : entries.keySet()) {
            if (matcher.match((String) o, uri.getPath()) &&
                    authorities.size() < Convert.toList(String.class, entries.get(o)).size()) {
                value = entries.get(o);
                authorities = Convert.toList(String.class, value);
                break;
            }
        }



        log.info("接口判断:{}" + uri.getPath() + " " + authorities);
        //认证通过且角色匹配的用户可访问当前路径
        return mono
                //判断是否认证成功
                .filter(Authentication::isAuthenticated)
                //获取认证后的全部权限
                .flatMapIterable(Authentication::getAuthorities)
                .map(GrantedAuthority::getAuthority)
                //如果权限包含则判断为true
                .any(authorities::contains)
                .map(AuthorizationDecision::new)
                .defaultIfEmpty(new AuthorizationDecision(false));
    }

}